<template>
  <div class="app-container">
    <el-card id="dlls_card" class="box-card" style="min-height: 900px;">
      <el-tabs v-model="activeName">
        <!--<el-tab-pane label="视频库" name="video_stores">-->
          <el-row :gutter="20">
            <el-col :span="6">
              <el-card class="box-card">
                <div slot="header" class="clearfix">
                  <span>文件目录</span>
                  <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
                </div>
                <div>
                  <el-tree
                    ref="trees"
                    :load="loadNode"
                    lazy
                    node-key="id"
                    highlight-current
                    :props="defaultProps"
                    :current-node-key="current_fold_id"
                    :expand-on-click-node="false"
                    @node-click="handleNodeClick"
                  >
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                      <!-- <span>{{data.name}}</span> -->
                      <!-- 编辑和删除 -->
                      <el-dropdown
                        trigger="hover"
                        @command="folderBatchAction($event, node, data)"
                      >
                        <span>{{ data.name }}</span>
                        <el-dropdown-menu slot="dropdown">
                          <el-dropdown-item command="edit"
                          >修改名称</el-dropdown-item
                          >
                          <el-dropdown-item command="delete">
                            删除文件夹
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </el-dropdown>
                    </span>
                  </el-tree>
                  <!-- :current-node-key="1"
                    :default-expanded-keys="[1]" -->
                </div>
              </el-card>
            </el-col>
            <el-col :span="18">
              <!-- 导航栏 -->
              <div style="display: flex;justify-content: flex-start;">
                <span
                  class="cursor_pointer"
                  :style="{
                    color:
                      !current_node || !current_node.parent.data
                        ? '#bbb'
                        : '#000',
                  }"
                  @click="returnLast"
                >返回</span
                >&nbsp;|&nbsp;<span
                class="cursor_pointer"
                :style="{
                    color:
                      !current_node || !current_node.parent.data
                        ? '#bbb'
                        : '#000',
                  }"
                @click="returnLast"
              >向上一级</span
              >&nbsp;<span v-show="selectFolderDirectoryPath"
              >|&nbsp;{{ selectFolderDirectoryPath }}</span
              >
              </div>
              <!-- 搜索栏 -->
              <div
                style="
                  margin: 10px 0;
                  display: flex;
                  align-items: center;
                  flex-wrap: wrap;
                  gap: 5px;
                "
              >
                <div class="">
                  <el-button type="primary" @click="showCreateFolderDialog"
                  >新建文件夹</el-button
                  >
                </div>
                <div class="searchItem">
                  <el-button type="default" @click="showUploadDialog"
                  >上传</el-button
                  >
                </div>
                <div class="searchItem">
                  <el-dropdown trigger="hover" @command="batchAction">
                    <el-button
                      type="default"
                      :disabled="selectionVideoData.length == 0"
                    >
                      <i
                        class="el-icon-document-add"
                        style="margin-right: 10px"
                      ></i
                      >批量操作
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="delete"
                      >批量删除</el-dropdown-item
                      >
                      <!-- <el-dropdown-item command="download">批量下载</el-dropdown-item> -->
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
                <div class="searchItem">
                  <span class="searchItemText" @click="refreshData">
                    <i class="el-icon-refresh-right"></i>刷新
                  </span>
                </div>

                <div style="white-space: nowrap; padding: 0 10px">
                  上传日期：
                  <el-date-picker
                    v-model="uploadDate"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  >
                  </el-date-picker>
                </div>

                <div class="searchItem">
                  <el-input
                    style="width: 150px"
                    v-model="videoData.keyword"
                    placeholder="请输入搜索内容"
                    suffix-icon="el-icon-search"
                    @change="refreshData"
                  />
                </div>
              </div>
              <!-- 表格栏 -->
              <div>
                <el-table
                  ref="videoTable"
                  border
                  style="width: 100%"
                  max-height="450"
                  :data="videoData.tableData"
                  @selection-change="handleSelectionPackageChange"
                >
                  <el-table-column type="selection" width="55">
                  </el-table-column>
                  <template v-for="item in tableHeadVideo">
                    <el-table-column
                      v-if="item.prop == 'operation'"
                      :key="item.prop"
                      :prop="'operation'"
                      label="操作"
                      :align="'center'"
                    >
                      <!-- :width="item.width" -->
                      <template slot-scope="{ row, column, $index }">
                        <div>
                          <span class="actionItem" @click="onDownloadVideo(row)"
                          >下载</span
                          >
                          <el-divider direction="vertical"></el-divider>
                          <el-popconfirm
                            title="确定删除该素材？"
                            @confirm="onRemoveVideo([row.id])"
                          >
                            <span class="actionItem" slot="reference"
                            >删除</span
                            >
                          </el-popconfirm>
                          <!-- <el-divider direction="vertical"></el-divider>
                          <span class="actionItem" @click="onDerive(row)">衍生</span> -->
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column
                      v-else-if="item.prop == 'name'"
                      :prop="item.prop"
                      :key="item.prop"
                      :label="item.label"
                      :width="item.width"
                      :align="item.align || 'center'"
                      :sortable="item.sortable"
                    >
                      <template slot-scope="{ row, column, $index }">
                        <div>
                          <video
                            :src="row.url"
                            controls
                            width="200"
                            height="100"
                          ></video>
                          <div>{{ row.name }}</div>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column
                      v-else
                      :prop="item.prop"
                      :key="item.prop"
                      :label="item.label"
                      :width="item.width"
                      :align="item.align || 'center'"
                      :sortable="item.sortable"
                    >
                    </el-table-column>
                  </template>
                </el-table>
                <div class="" style="margin-top: 10px; float: right">
                  <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleVideoCurrentChange"
                    :page-sizes="[10, 15, 20, 25, 50]"
                    :current-page.sync="videoData.page"
                    :page-size="page_size"
                    layout="sizes, prev, pager, next, total"
                    :total="videoData.total"
                  >
                  </el-pagination>
                </div>
              </div>
            </el-col>
          </el-row>
        <!--</el-tab-pane>-->
      </el-tabs>
    </el-card>
    <upload-file-dialog
      :visible="uploadFileData.visible"
      :currentFoldId="current_fold_id"
      :currentNode="current_node"
      :selectFolderDirectoryPaths="selectFolderDirectoryPath"
      @changeVisible="changeUploadFileVisible"
    ></upload-file-dialog>
    <create-folder-dialog
      :visible="createNewFolderDialog.visible"
      @changeVisible="changeCreateNewFolderVisible"
      @changeFolderDirectory="changeFolderDirectory"
    >
    </create-folder-dialog>
    <!-- 修改文件夹名称 -->
    <el-dialog
      title="修改名称"
      :visible.sync="updateFolderNameDialog.visible"
      class="btwaDialog"
      width="600px"
      :before-close="closeUpdateFolderDialog"
    >
      <div>
        <div class="formItem">
          <div style="width: 100px; white-space: nowrap; text-align: right">
            文件夹名：
          </div>
          <el-input
            style="width: 300px"
            placeholder="请输入"
            v-model="updateFolderNameDialog.folderName"
          />
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeUpdateFolderDialog()">取 消</el-button>
        <el-button type="primary" @click="onUpdateFolderNameOk"
        >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getFolders,
    getMaterialList,
    batchDeleteVideo,
    updateFolderName,
    removeFolder,
  } from "../../api";
  import UploadFileDialog from "./UploadFileDialog";
  import CreateFolderDialog from "./CreateFolderDialog";
  import moment from "moment";
  import SparkMD5 from "spark-md5";
  const COS = require("cos-js-sdk-v5");
  const cos = new COS({
    SecretId: "AKIDhK6oW96L8mJbKvreiZCpXIw6h973lBKH",
    SecretKey: "rWzJROAlA5mNsBJH2auyxqYi2EAvYYMw",
    Protocol: "https:",
  });
  export default {
    name: "App",
    components: {
      UploadFileDialog,
      CreateFolderDialog,
    },
    data() {
      return {
        updateFolderNameDialog: {
          visible: false,
          folderNode: null,
          folder: null,
          folderName: null,
        },
        createNewFolderDialog: {
          visible: false,
          data: null,
          id: null, // 刷新的层级id
        },
        uploadDate: "",
        current_fold_id: null, // 当前的文件id
        current_node: null, // 当前选中的节点
        current_path_list: [], // 当前选中的节点路径list
        selectFolderDirectoryPath: "", // 当前选中的节点路径组装名
        uploadFileData: {
          visible: false,
          dataList: [],
        },
        count: 0,
        activeName: "video_stores",
        page_size: 15,
        loading: false,
        defaultProps: {
          label: "name",
          children: "name",
        },
        videoData: {
          keyword: "",
          tableData: [],
          page: 1,
          total: 0,
        },
        selectionVideoData: [],
        tableHeadVideo: [
          {
            label: "视频",
            prop: "name",
            width: 300,
            sortable: false,
          },
          {
            label: "ID",
            prop: "id",
            // prop: "id",
            width: 150,
            sortable: true,
          },
          {
            label: "操作",
            prop: "operation",
            // width: 150,
            sortable: false,
          },
          {
            label: "审核状态",
            prop: "pre_audit_status",
            width: 100,
            sortable: false,

          } ,{
            label: "拒绝原因",
            prop: "reject_reason",
            width: 100,
            sortable: false,

          }
        ],
      };
    },
    watch: {
      uploadDate: {
        handler(newV, oldV) {
          console.log("uploadDatenewV", newV);
        },
        immediate: false,
      },
    },
    computed: {
      accountsMap() {
        return 1;
      },
    },
    async created() {},
    mounted() {
      // this.$refs.trees.setCurrentKey(2)
      // this.loadData(0)
    },
    methods: {
      returnLast() {
        if (!this.current_node || !this.current_node.parent.data) {
          return;
        }
        this.current_path_list = [];
        this.getFolderPath(this.current_node.parent);
        this.selectFolderDirectoryPath = this.current_path_list.join(" / ");
        this.current_fold_id = this.current_node.data.parent_id;
        this.current_node = this.current_node.parent;
        this.$nextTick(() => {
          this.$refs.trees.setCurrentKey(this.current_fold_id);
        });
        this.loadData();
      },
      async onRemoveFolder(node, data) {
        let res = await removeFolder({
          id: data.id,
        }).catch((e) => e);
        if (res.code == 200 || res.msg == "success") {
          this.$message.success("删除成功");
          let fatherNodes = this.$refs.trees.getNode(data.parent_id);
          if (!fatherNodes) {
            // 查询不到证明未加载该节点
            return;
          }
          fatherNodes.loaded = false;
          fatherNodes.expand();
        } else {
          this.$message.error(res.msg);
        }
      },
      async onUpdateFolderNameOk() {
        let res = await updateFolderName({
          id: this.updateFolderNameDialog.folder.id,
          name: this.updateFolderNameDialog.folderName,
        }).catch((e) => e);
        if (res.code == 200 || res.msg == "success") {
          this.$message.success("修改成功");
          this.updateFolderNameDialog.visible = false;
          let fatherNodes = this.$refs.trees.getNode(
            this.updateFolderNameDialog.folder.parent_id
          );
          if (!fatherNodes) {
            // 查询不到证明未加载该节点
            return;
          }
          fatherNodes.loaded = false;
          fatherNodes.expand();
        } else {
          this.$message.error(res.msg);
        }
      },
      closeUpdateFolderDialog(done) {
        this.updateFolderNameDialog.visible = false;
        if (done) {
          done();
        }
      },
      changeFolderDirectory(id, node) {
        if (id) {
          let createFolderByNodes = this.$refs.trees.getNode(id);
          if (!createFolderByNodes) {
            // 查询不到证明未加载该节点
            return;
          }
          createFolderByNodes.loaded = false;
          createFolderByNodes.expand();
        } else {
          let fatherNodes = this.$refs.trees.root;
          if (!fatherNodes) {
            return;
          }
          fatherNodes.loaded = false;
          fatherNodes.expand();
        }
      },
      changeCreateNewFolderVisible(value) {
        this.createNewFolderDialog.visible = value;
      },
      refresh() {
        // 添加传当前节点，编辑传父节点
        let node = this.$refs.trees.getNode(this.id);
        node.loaded = false;
        node.expand();
      },
      folderBatchAction(e, node, data) {
        console.log(e, node, data, "folderBatchAction");
        if (e == "edit") {
          // 编辑
          this.updateFolderNameDialog.folderNode = node;
          this.updateFolderNameDialog.folder = data;
          this.updateFolderNameDialog.folderName = data.name;
          this.updateFolderNameDialog.visible = true;
        } else {
          // 删除
          this.$confirm("此操作将永久删除该文件夹, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.onRemoveFolder(node, data);
            })
            .catch(() => {
              console.log("取消删除");
            });
        }
      },
      async loadData() {
        let { page_size, videoData } = this;
        let params = {
          page: videoData.page,
          page_size,
          folder_id: this.current_fold_id,
          name: videoData.keyword,
          start_date: this.uploadDate
            ? moment(this.uploadDate[0]).format("YYYY-MM-DD")
            : null,
          end_date: this.uploadDate
            ? moment(this.uploadDate[1]).format("YYYY-MM-DD")
            : null,
        };
        let res = await getMaterialList(params).catch((e) => e);
        if (res.code == 200 || res.msg == "success") {
          this.videoData.tableData = res.data.list.map((item) => {
            return {
              ...item,
              key: item.id,
            };
          });
          this.videoData.total = res.data.count;
        } else {
          this.$message.error("获取失败");
        }
      },
      getFolderPath(currentNode) {
        if (currentNode.parent && currentNode.parent.data) {
          this.getFolderPath(currentNode.parent);
          this.current_path_list.push(currentNode.data.name);
        } else {
          this.current_path_list.push(currentNode.data.name);
        }
      },
      changeUploadFileVisible(value) {
        this.uploadFileData.visible = value;
      },
      handleSizeChange(val) {
        this.videoData.page = 1;
        this.page_size = val;
        this.loadData();
      },
      handleVideoCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.videoData.page = val;
        // 获取视频列表
        this.loadData();
      },
      onDownloadVideoBatch(row, triggerDelay, removeDelay) {
        let list = row.url.split("/");
        let name = list[list.length - 1];
        cos.getObjectUrl(
          {
            Bucket: "bdw-sh-1259268558",
            Region: "ap-shanghai",
            Key: name /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），支持中文，必须字段 */,
            Sign: true,
          },
          function (err, data) {
            if (err) return console.log(err);
            var downloadUrl =
              data.Url +
              (data.Url.indexOf("?") > -1 ? "&" : "?") +
              "response-content-disposition=attachment"; // 补充强制下载的参数
            /* 可拼接 filename 来实现下载时重命名 */
            /* downloadUrl += ';filename=myname'; */
            // （推荐使用 window.open()方式）这里是新窗口打开 url，如果需要在当前窗口打开，可以使用隐藏的 iframe 下载，或使用 a 标签 download 属性协助下载

            setTimeout(function () {
              const frame = document.createElement("iframe");
              frame.src = downloadUrl;
              frame.style.display = "none";
              document.body.appendChild(frame);
              setTimeout(function () {
                frame.remove();
              }, removeDelay);
            }, triggerDelay);
            // setTimeout(function () {
            //   const a = document.createElement('a');
            //   a.style.display = 'none';
            //   a.href = downloadUrl;
            //   a.download = row.name;
            //   document.body.appendChild(a);
            //   a.click();
            //   document.body.removeChild(a);
            // }, triggerDelay)
          }
        );
      },
      onDownloadVideo(row) {
        // const iframe = document.createElement("iframe")
        // iframe.style.display = "none";
        // iframe.style.height = 0;
        // iframe.src = row.url;
        // document.body.appendChild(iframe);
        // setTimeout(()=>{
        //   iframe.remove();
        // },120000)

        // const a = document.createElement('a');
        // a.style.display = 'none';
        // a.href = row.url;
        // a.download = row.name;
        // document.body.appendChild(a);
        // a.click();
        // document.body.removeChild(a);

        // let x = new XMLHttpRequest();
        // x.open('GET', row.url, true);
        // x.responseType = 'blob';
        // x.onload = function() {
        //   const nurl = window.URL.createObjectURL(x.response)
        //   const eleLink = document.createElement('a');
        //   eleLink.href = nurl;
        //   eleLink.download = `${row.name}`;
        //   eleLink.style.display = 'none';
        //   document.body.appendChild(eleLink);
        //   eleLink.click();
        //   document.body.removeChild(eleLink);
        //   window.URL.revokeObjectURL(nurl);
        // }
        // x.send();

        // const a = document.createElement('a')
        // fetch(row.url).then(res => res.blob()).then(blob => { // 将链接地址字符内容转变成blob地址
        //   a.href = URL.createObjectURL(blob)
        //   console.log(a.href)
        //   a.download = row.name // 下载文件的名字
        //   document.body.appendChild(a)
        //   a.click()
        //   //在资源下载完成后 清除 占用的缓存资源
        //   window.URL.revokeObjectURL(a.href);
        //   document.body.removeChild(a);
        // })
        let list = row.url.split("/");
        let name = list[list.length - 1];
        cos.getObjectUrl(
          {
            Bucket: "bdw-sh-1259268558",
            Region: "ap-shanghai",
            Key: name /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），支持中文，必须字段 */,
            Sign: true,
          },
          function (err, data) {
            if (err) return console.log(err);
            var downloadUrl =
              data.Url +
              (data.Url.indexOf("?") > -1 ? "&" : "?") +
              "response-content-disposition=attachment"; // 补充强制下载的参数
            /* 可拼接 filename 来实现下载时重命名 */
            /* downloadUrl += ';filename=myname'; */
            // （推荐使用 window.open()方式）这里是新窗口打开 url，如果需要在当前窗口打开，可以使用隐藏的 iframe 下载，或使用 a 标签 download 属性协助下载
            window.open(downloadUrl);
          }
        );
      },
      async onRemoveVideo(ids) {
        let res = await batchDeleteVideo({
          ids,
        }).catch((e) => e);
        if (res.code == 200 || res.msg == "success") {
          this.$message.success("删除成功");
          this.loadData();
        } else {
          this.$message.error(res.msg);
        }
      },
      onDerive() {},
      handleSelectionPackageChange(val) {
        console.log(val);
        this.selectionVideoData = val;
        // this.$emit("handleSelectionChange", val); /* 向外暴露set方法 */
      },
      refreshData() {
        this.loadData();
      },
      batchAction(command) {
        let vm = this;
        if (command == "delete") {
          console.log("批量删除");
          this.$confirm("确定删除选中的素材？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(async () => {
              console.log("确认删除");
              let ids = this.selectionVideoData.map((item) => {
                return item.id;
              });
              let res = await batchDeleteVideo({
                ids,
              }).catch((e) => e);
              if (res.code == 200 || res.msg == "success") {
                vm.$message.success("删除成功");
                vm.loadData();
              } else {
                vm.$message.error(res.msg);
              }
            })
            .catch(() => {
              console.log("取消删除");
            });
        } else {
          console.log("批量下载");
          this.selectionVideoData.forEach((item, index) => {
            this.onDownloadVideoBatch(item, index * 100, 1000);
          });
        }
      },
      showCreateFolderDialog() {
        this.createNewFolderDialog.visible = true;
      },
      showUploadDialog() {
        this.uploadFileData.visible = true;
        this.loadNode(0)
      },
      async getFolderList(id) {
        let res = await getFolders({ parent_id: id }).catch((e) => e);
        if (res.code == 200 || res.msg == "success") {
          return res.data.list;
        } else {
          this.$message.error("获取文件夹列表失败");
          return false;
        }
      },
      async loadNode(node, resolve) {
        console.log("node, resolve");
        console.log(node);
        console.log(resolve);
        if (node.level >= 0 && node.level < 3) {
          // 限制最多3级
          let list = await this.getFolderList(node.data ? node.data.id : 0);
          if (list && list.length > 0 && node.level == 0) {
            this.current_fold_id = list[0].id;
            this.selectFolderDirectoryPath = list[0].name;
            this.$nextTick(() => {
              this.$refs.trees.setCurrentKey(list[0].id);
            });
            this.loadData();
          }
          return resolve(list || []);
        }
        if (node.level >= 3) {
          return resolve([]);
        }
      },
      handleNodeClick(data, node, myself) {
        console.log(node);
        if (data.id != this.current_fold_id) {
          this.current_fold_id = data.id;
          this.current_node = node;
          this.current_path_list = [];
          this.getFolderPath(node);
          this.selectFolderDirectoryPath = this.current_path_list.join(" / ");
        }
        this.loadData();
      },
    },
  };
</script>

<style lang="scss">
  html,
  body {
    height: 100%;
  }

  .scroll::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 10px;
    /*高宽分别对应横竖滚动条的尺寸*/
    height: 12px;
  }

  .scroll::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 8px;
    -webkit-box-shadow: inset 0 0 5px rgba(255, 255, 255, 0.2);
    background: #fff;
  }

  .scroll::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.8);
    border-radius: 10px;
    background: #888;
  }

  ul,
  li {
    list-style: none;
  }

  .cl::after {
    display: block;
    width: 0;
    height: 0;
    content: "";
    clear: both;
  }

  .fr {
    float: right;
  }

  .fl {
    float: left;
  }

  .el-icon-error {
    cursor: pointer;
  }

  .btwaDialog {
    .item {
      background: #e9ecf1;
      border-radius: 3px;
      line-height: 22px;
      padding: 5px;
      margin-bottom: 8px;

      p {
        margin: 0px;
      }
    }
  }

  .searchItem {
    padding: 0px 10px;
    .searchItemText {
      cursor: pointer;
      &:hover {
        color: "#409eff";
      }
    }
  }
  .actionItem {
    cursor: pointer;
    color: #409eff;
  }
  .formItem {
    display: flex;
    padding-bottom: 10px;
    width: 100%;
  }
  .cursor_pointer {
    cursor: pointer;
  }
</style>
